<template>
  <div class="the-list">
    <div class="panel-search">
      <el-form inline :model="tableData.query" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input
            v-model="tableData.query.eventsOrderNo"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>

        <el-form-item label="活动ID">
          <el-input
            v-model="tableData.query.eventsId"
            placeholder="请输入活动ID"
            clearable
          />
        </el-form-item>
		
        <el-form-item label="活动名称">
          <el-input
            v-model="tableData.query.eventsName"
            placeholder="请输入活动名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="报名时间">
          <el-date-picker
            :model-value="tableData.special.createdAt"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @update:modelValue="tableFn.detetimeChange($event, 'submit')"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="tableFn.onSubmit">搜索</el-button>
          <el-button type="primary" @click="tableFn.onResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="panel-table">
      <el-tabs @tab-click="tableFn.handleClick" v-model="activeTab">
        <el-tab-pane
          v-for="(item, index) in tableData.orderstatusList"
          :name="item.orderStatus"
          :label="item.tabName"
          :key="index"
        >
          <div class="table-head">
            <div>订单列表</div>
          </div>
          <el-table
            :data="tableData.list"
            stripe
            :header-cell-style="{
              backgroundColor: '#ededed',
              padding: '12px 0',
            }"
            style="width: 100%"
            border
          >
            <el-table-column prop="eventsOrderNo" label="订单号" />
            <el-table-column prop="eventsName" label="活动名称" />
            <el-table-column prop="applyName" label="报名人" />
            <el-table-column prop="customerName" label="用户名称" />
            <el-table-column prop="customerId" label="用户id" />
            <el-table-column prop="createdAt" label="报名时间" />
            <el-table-column prop="orderStatus" label="状态">
              <template #default="{ row }">
                {{
                  tableFn.getItemFromArray(
                    tableData.statusList,
                    row.orderStatus
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column prop="personNum" label="参与人数">
              <template #default="{ row }">
                {{ row.personNum || '未填写' }}
              </template>
            </el-table-column>
            <el-table-column prop="petNum" label="参与宠物数">
              <template #default="{ row }">
                {{ row.petNum || '未填写' }}
              </template>
            </el-table-column>
            <el-table-column prop="payMoney" label="费用（元）" >
              <template #default="{ row }">
                {{
                  row.payMoney/100
                }}
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="330px"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  plain
                  @click="tableFn.goToDetail(row)"
                  >详情</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  v-if="
                    item.orderStatus == '0' &&
                    hasPermission(['content:toggleStatus'])
                  "
                  plain
                  @click="updateMoneyFn.openDialog(row)"
                  >修改金额</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  v-if="
                    item.orderStatus == '1' &&
                    hasPermission(['orderCare:eventsOrder:refund'])
                  "
                  plain
                  @click="refundFn.openDialog(row)"
                  >退款</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  v-if="item.orderStatus != '4' && item.orderStatus != '3'"
                  plain
                  @click="updateMoneyRecordFn.openDialog(row)"
                  >修改金额记录</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="table-pagination">
        <pagination
          :total="tableData.total"
          v-model:page="tableData.query.page"
          v-model:limit="tableData.query.pageSize"
          @pagination="tableFn.getTableList"
        />
      </div>
    </div>

    <!--修改金额弹窗-->
    <el-dialog v-model="updateMoneyData.updateMoneyVisible" title="修改金额">
      <el-form
        :model="updateMoneyData.obj"
        ref="updateMoneyForm"
        :rules="updateMoneyData.updateMoneyRules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="金额" label-width="80px" prop="copyPayMoney">
              <div style="display: flex">
                <el-input
                  maxlength="20"
                  v-model="updateMoneyData.obj.copyPayMoney"
                  autocomplete="off"
                  @input="updateMoneyFn.payMoneyChangeHandle"
                />
                <text>元</text>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" label-width="80px" prop="updateRemark">
              <el-input
                maxlength="255"
                type="textarea"
                v-model="updateMoneyData.obj.updateRemark"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateMoneyFn.closeDialog">取消</el-button>
          <el-button
            type="primary"
            @click="updateMoneyFn.updateMoneySubmit(updateMoneyForm)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!--金额修改记录查看弹窗-->
    <el-dialog
      v-model="updateMoneyRecordData.updateMoneyRecordVisible"
      title="金额修改记录"
    >
      <el-table
        max-height="450px"
        :data="updateMoneyRecordData.updateMoneyRecordList"
        stripe
        :header-cell-style="{ backgroundColor: '#ededed', padding: '12px 0' }"
        style="width: 100%"
        border
      >
        <el-table-column prop="updateName" label="修改人" />
        <el-table-column prop="createdAt" label="修改时间" />
        <el-table-column prop="brforePrice" label="修改前价格">
          <template #default="scope">
            <text>{{ scope.row.brforePrice/100 }}元</text>
          </template>
        </el-table-column>
        <el-table-column prop="laterPrice" label="修改后价格">
          <template #default="scope">
            <text>{{ scope.row.laterPrice/100 }}元</text>
          </template>
        </el-table-column>
        <el-table-column prop="updateRemark" label="修改备注" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateMoneyRecordFn.closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!--退款-->
    <el-dialog v-model="refundData.refundVisible" title="退款">
      <el-form
        :model="refundData.obj"
        ref="refundForm"
        :rules="refundData.refundRules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="退款金额" label-width="80px" prop="sourcePayMoney">
              <div style="display: flex">
                <el-input
                  maxlength="20"
                  v-model="refundData.obj.sourcePayMoney"
                  autocomplete="off"
                  @input="refundFn.payMoneyChangeHandle"
                />
                <text>元</text>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundFn.closeDialog">取消</el-button>
          <el-button type="primary" @click="refundFn.refundSubmit(refundForm)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref } from "vue";
import { getEventsOrderList, updateMoney, refund } from "@/api/eventsOrder.js";
import { getOrderPriceUpdateRecordByOrderId } from "@/api/OrderPriceUpdateRecord.js";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getItemFromArray } from "@/utils/tool";

export default {
  name: "eventsOrderManage",
  components: {},
  setup() {
    const { $data: tableData, $fn: tableFn } = tableModule();
    const { $data: updateMoneyData, $fn: updateMoneyFn } =
      updateMoneyModule(tableFn);
    const { $data: updateMoneyRecordData, $fn: updateMoneyRecordFn } =
      updateMoneyRecordModule();
    const { $data: refundData, $fn: refundFn } = refundModule();

    const updateMoneyForm = ref(null);
    const refundForm = ref(null);

    return {
      tableData,
      tableFn,
      updateMoneyData,
      updateMoneyFn,
      updateMoneyForm,
      updateMoneyRecordData,
      updateMoneyRecordFn,
      refundData,
      refundFn,
      refundForm,
    };
  },
  data() {
  	return {
  	  activeTab: '1' // 设置默认进入的 tab，使用 '1' 对应已支付的 orderStatus
  	};
  }
};

// 表格功能模块，包括搜索，分页等
function tableModule() {
  const router = useRouter();

  const backup = {
    query: {
      orderStatus: "",
      eventsOrderNo: "", // 订单号
      eventsName: "", // 活动名称
      createdAtStart: "", //提交时间-起(订单创建时间)
      createdAtEnd: "", //提交时间-止
      pageSize: 10,
      page: 1,
    },
  };

  const $data = reactive({
    query: { ...backup.query },
    special: {
      createdAt: [],
    },
    list: [],
    total: 0,
    statusList: [
      { key: "0", name: "待支付" },
      { key: "1", name: "已支付" },
      { key: "2", name: "已完成" },
      { key: "3", name: "已取消" },
      { key: "4", name: "已退款" },
    ],
    orderstatusList: [
      {
        tabName: "待支付",
        orderStatus: "0",
        tableCode: "eventsOrder0",
      },
      {
        tabName: "已支付",
        orderStatus: "1",
        tableCode: "eventsOrder1",
      },
      {
        tabName: "已完成",
        orderStatus: "2",
        tableCode: "eventsOrder2",
      },
      {
        tabName: "已取消",
        orderStatus: "3",
        tableCode: "eventsOrder3",
      },
      {
        tabName: "已退款",
        orderStatus: "4",
        tableCode: "eventsOrder4",
      },
    ],
  });
  const $fn = {
    handleClick({ props }) {
      $data.query.orderStatus = props.name;
      $fn.getTableList();
    },
    // 获取表数据
    getTableList() {
      if (!$data.query.orderStatus) {
        $data.query.orderStatus = "1";
      }
      getEventsOrderList($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    // 重置
    onResetQuery() {
      let orderStatus = $data.query.orderStatus;
      $data.query = { ...backup.query };
      $data.query.orderStatus = orderStatus;
      $data.special.createdAt = [];
      $fn.getTableList();
    },
    // 搜索
    onSubmit() {
      $fn.getTableList();
    },
    detetimeChange(time, type) {
      time = time || [];
      if (type === "submit") {
        $data.special.createdAt = time;
        $data.query.createdAtStart = time[0] || "";
        $data.query.createdAtEnd = time[1] || "";
      }
    },
    // 详情
    goToDetail(row, view) {
      router.push(
        `/orderCare/eventsOrder/seeOrderDetail/${row.id}?view=eventsOrder_index&operation=see`
      );
    },
    getItemFromArray(itemList, item) {
      return getItemFromArray(itemList, item);
    },
  };

  $fn.getTableList();

  return {
    $data,
    $fn,
  };
}

// 修改金额
function updateMoneyModule(tableFn) {
  const $data = reactive({
    obj: {},
    updateMoneyVisible: false,
    updateMoneyRules: {
      copyPayMoney: [
        { required: true, message: "请输入金额", trigger: "blur" },
      ],
      updateRemark: [
        { required: true, message: "请填写备注", trigger: "blur" },
      ],
    },
  });
  const $fn = {
    updateMoneySubmit(formEl) {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          $data.obj.type = "0";
          $data.obj.payMoney = $data.obj.copyPayMoney*100
          updateMoney($data.obj).then((res) => {
            if (res.code == 0) {
              ElMessage.success("操作成功");
              $fn.closeDialog();
              tableFn.getTableList();
            }
          });
        } else {
          return false;
        }
      });
    },
    payMoneyChangeHandle(value) {
      $data.obj.copyPayMoney = commonFunction().$fn.disposeInputValue(value);
    },
    // obj：被修改对象
    openDialog(obj) {
      if (!obj || !obj.id) {
        $data.updateMoneyVisible = false;
        return ElMessage.warning("修改对象不存在，请刷新页面重试");
      }
      // 备份原金额
      obj.copyPayMoney = obj.payMoney/100;
      $data.obj = JSON.parse(JSON.stringify(obj));
      $data.updateMoneyVisible = true;
    },
    closeDialog() {
      $data.obj = {};
      $data.updateMoneyVisible = false;
    },
  };
  return {
    $data,
    $fn,
  };
}

// 金额修改记录查看相关
function updateMoneyRecordModule() {
  const $data = reactive({
    updateMoneyRecordList: [],
    updateMoneyRecordVisible: false,
  });
  const $fn = {
    // obj：被修改对象
    openDialog(obj) {
      if (!obj || !obj.id) {
        $data.updateMoneyRecordVisible = false;
        return ElMessage.warning("订单对象不存在，请刷新页面重试");
      }
      // 获取金额修改记录list
      getOrderPriceUpdateRecordByOrderId(obj.id, "0").then((res) => {
        if (res.code == 0) {
          $data.updateMoneyRecordList = res.data;
        }
      });
      $data.updateMoneyRecordVisible = true;
    },
    closeDialog() {
      $data.updateMoneyRecordVisible = false;
      $data.updateMoneyRecordList = [];
    },
  };
  return {
    $data,
    $fn,
  };
}

// 退款
function refundModule() {
  const $data = reactive({
    obj: {},
    refundVisible: false,
    refundRules: {
      sourcePayMoney: [
        { required: true, message: "请输入退款金额", trigger: "blur" },
      ],
    },
  });
  const $fn = {
    refundSubmit(formEl) {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          if ($data.obj.payMoney == 0) {
            return ElMessage.warning("退款金额不能为0");
          }
          if($data.obj.sourcePayMoney*100 > $data.obj.payMoney){
            return ElMessage.warning(
              "退款金额不能大于申请金额：" + $data.obj.payMoney/100 + "元"
            );
          }
          $data.obj.type = "0";
          $data.obj.payMoney = $data.obj.sourcePayMoney*100
          refund($data.obj).then((res) => {
            if (res.code == 0) {
              ElMessage.success("操作成功");
              $fn.closeDialog();
            }
          });
        } else {
          return false;
        }
      });
    },
    // obj：被修改对象
    openDialog(obj) {
      if (!obj || !obj.id) {
        $fn.closeDialog();
        return ElMessage.warning("订单对象不存在，请刷新页面重试");
      }
      $data.obj.id = obj.id;
      $data.obj.payMoney = obj.payMoney;
      $data.obj.sourcePayMoney = $data.obj.payMoney/100;
      $data.refundVisible = true;
    },
    closeDialog() {
      $data.refundVisible = false;
      $data.obj = {};
    },
    payMoneyChangeHandle(value){
      $data.obj.sourcePayMoney = commonFunction().$fn.disposeInputValue(value)
    },
  };
  return {
    $data,
    $fn,
  };
}

function commonFunction() {
  const $data = reactive({});

  const $fn = {
    disposeInputValue(num) {
      if (!num && num != "0") {
        return "";
      }
      let str = num;
      let len1 = str.substr(0, 1);
      let len2 = str.substr(1, 1);
      //如果第一位是0，第二位不是点，就用数字把点替换掉【去掉数字前面无用的0】
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      //第一位不能是.
      if (len1 == ".") {
        str = "";
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      //正则替换
      str = str.replace(/[^\d^.]+/g, ""); // 保留数字和小数点
      if (str.indexOf(".") == -1 || str.indexOf(".") == str.length - 1) {
        return str;
      }
      let tempNum = str * 100;
      tempNum = parseInt(tempNum);
      str = tempNum / 100;
      return str;
    },
    /***
     * 获取请求的UUID，指定长度和进制,如
     * getUUID(8, 2)   //"01001010" 8 character (base=2)
     * getUUID(8, 10) // "47473046" 8 character ID (base=10)
     * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
     */
    getUUID(len, radix) {
      let chars =
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
          ""
        );
      let uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (let i = 0; i < len; i++)
          uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (let i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    },
  };

  return {
    $data,
    $fn,
  };
}
</script>

<style scoped lang="scss">
@import "@/styles/tablePage.scss";
:deep(.el-tabs__nav-wrap::after) {
  background-color: transparent !important;
}
</style>

